# coding:utf-8

from flask import Flask, request
import baseCaseBussiness
import json, time
import appconf, hashlib, os
from flask import send_from_directory
import xlsReader

app = appconf.app


@app.route('/basecase/casePlan/exist')
def basecase_casePlan_exist():
    project_id = request.args.get("project_id")
    case_plan = request.args.get("case_plan")
    isExist = baseCaseBussiness.baseCase_isCasePlan_exist(project_id, case_plan)
    return json.dumps({'errorCode': '', 'isExist': isExist})


@app.route('/basecase/casepaln/all')
def basecase_casePlan_all():
    project_id = request.args.get("project_id")
    return json.dumps({'errorCode': '', 'data': baseCaseBussiness.baseCase_allPlan(project_id)})


@app.route('/basecase/caseMainMod/all')
def basecase_caseMainMoudle_all():
    project_id = request.args.get("project_id")
    case_plan = request.args.get("case_plan")
    return json.dumps({'errorCode': '', 'data': baseCaseBussiness.baseCase_allModel(project_id, case_plan)})


@app.route('/basecase/case/srh')
def basecase_case_srh_all():
    project_id = request.args.get("project_id")
    case_plan = request.args.get("case_plan")
    main_module = request.args.get("main_module")
    case_pri = request.args.get("case_pri")
    key_words = request.args.get("key_words")
    page = request.args.get("page")
    limit = request.args.get("limit")
    items = baseCaseBussiness.baseCase_srh(project_id, case_plan, case_pri, main_module, key_words, page, limit)

    return json.dumps({'errorCode': '', 'data': items[0], "count": items[1]})


@app.route('/basecase/case/manage', methods=['POST'])
def basecase_case_manage():
    content = request.json
    id = baseCaseBussiness.baseCase_manage(content)
    return json.dumps({'errorCode': '', 'id': id})


@app.route('/basecase/case/del', methods=['POST'])
def basecase_case_del():
    content = request.json
    list = []
    for d in content:
        id = baseCaseBussiness.baseCase_del(d)
        list.append(id)
    return json.dumps({'errorCode': '', 'id': list})


@app.route('/basecase/case/manage/saveAll', methods=['POST'])
def basecase_case_manage_saveAll():
    content = request.json
    list = []
    for ctn in content:
        id = baseCaseBussiness.baseCase_manage(ctn)
        list.append(id)
    return json.dumps({'errorCode': '', 'id': list})


@app.route('/basecase/case/import/saveAll', methods=['POST'])
def basecase_case_import_saveAll():
    data = request.json
    content = data.get('data')
    list = []
    for ctn in content:
        if ctn == []: continue
        ctn['project_id'] = data.get('project_id')
        ctn['case_plan'] = data.get('case_plan')
        ctn['up_person'] = data.get('userId')
        ctn['in_person'] = data.get('userId')
        id = baseCaseBussiness.baseCase_manage(ctn)
        list.append(id)
    return json.dumps({'errorCode': '', 'id': list})


@app.route("/upload/files", methods=['POST'])
def upload_files():
    """测试用例，支持图片式编辑"""

    file = request.files['file']
    fileName = file.filename
    ext = fileName.rsplit('.', 1)[1]
    filePath = Md5.md5_string("%s" % int(time.time() * 1000)) + '.' + ext
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filePath))
    fileUrl = "/download/%s" % (filePath)

    return json.dumps({'errorCode': '', "url": fileUrl})


@app.route("/upload/xls", methods=['POST'])
def upload_files_xls():
    """测试用例，支持图片式编辑"""

    file = request.files['file']
    fileName = file.filename
    ext = fileName.rsplit('.', 1)[1]
    filePath = Md5.md5_string("%s" % int(time.time() * 1000)) + '.' + ext
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filePath))
    fileFullPath = app.config['UPLOAD_FOLDER'] + filePath
    t = xlsReader.ReadExcel(fileFullPath)
    data = t.read_data()
    #   定义一个方法用来解析xls文件中的内容
    return json.dumps({'errorCode': '', "data": data})


@app.route('/basecase/doCase/getTask')
def basecase_doCase_getTask():
    userId = request.args.get("userId")
    project_version = request.args.get("project_version")
    data = baseCaseBussiness.baseCase_gotMyDo(userId, project_version)
    return json.dumps({'errorCode': '', "data": data})


@app.route('/download/<filename>')
def down_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)


#######################################################测试结果的处理

@app.route('/basecase/case/do')
def basecase_case_alldoCase():
    project_id = request.args.get("project_id")
    project_version = request.args.get("project_version")
    case_pri = request.args.get("case_pri")
    result = request.args.get("result")
    case_main_mod_list = request.args.get("case_main_mod_list")
    case_plan = request.args.get("case_plan")
    key_words = request.args.get("key_words")

    page = request.args.get("page")
    limit = request.args.get("limit")

    items = baseCaseBussiness.baseCase_getTask_doCase(project_id, project_version, case_pri, result, case_main_mod_list,
                                                      case_plan, key_words, page, limit)
    return json.dumps({'errorCode': '', 'data': items[0], "count": items[1]})


@app.route('/basecase/case/result/manage', methods=['POST'])
def basecase_case_result_manage():
    content = request.json
    data = baseCaseBussiness.case_result_manage(content)
    return json.dumps({'errorCode': '', 'id': data})

@app.route('/basecase/case/result/historyFail')
def basecase_case_history_fail():
    caseId = request.args.get("case_id")
    resultId = request.args.get("resultId")
    data = baseCaseBussiness.case_result_history(caseId,resultId)
    return json.dumps({'errorCode': '', 'data': data})

@app.route('/basecase/case/result/delete', methods=['POST'])
def basecase_case_result_delete():
    content = request.json
    data = baseCaseBussiness.case_result_delete(content['id'])
    return json.dumps({'errorCode': '', 'id': data})


@app.route('/basecase/case/result/allDoVersion')
def basecase_case_history_allDoVersion():
    project_id = request.args.get("project_id")
    data = baseCaseBussiness.case_result_get_allDoVersion(project_id)
    return json.dumps({'errorCode': '', 'data': data})


@app.route('/basecase/case/hisResult/search')
def basecase_case_hisResult_search():
    project_id = request.args.get("project_id")
    project_version = request.args.get("project_version")
    result = request.args.get("result")
    key_words = request.args.get("key_words")
    page = request.args.get("page")
    limit = request.args.get("limit")

    items = baseCaseBussiness.case_result_search(project_id,project_version,result,key_words,page,limit)

    return json.dumps({'errorCode': '', 'data': items[0], "count": items[1]})

@app.route('/basecase/case/hisResult/sys/byMod')
def basecase_case_hisResult_sysByMoudle():
    project_id = request.args.get("project_id")
    project_version = request.args.get("project_version")
    items = baseCaseBussiness.case_result_sys_byModule(project_id,project_version)
    return json.dumps({'errorCode': '', 'data': items[0],"count": items[1]})

class Md5():
    def _file_as_bytes(self, file):
        with file:
            return file.read()

    @staticmethod
    def md5_string(str):
        """对字符串进行md5"""
        hl = hashlib.md5()
        hl.update(str.encode(encoding='utf-8'))
        return hl.hexdigest()

    @staticmethod
    def md5_file(file):
        """一般文件md5签名"""
        return hashlib.md5(Md5()._file_as_bytes(open(file, 'rb'))).hexdigest()
